package com.briup.smartcity_group6.web.interceptor;



import com.briup.smartcity_group6.exception.ServiceException;
import com.briup.smartcity_group6.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method  =request.getMethod();
        if("OPTIONS".equals(method))
        {
            return true;
        }
        //1.通过请求对象获取token auth请求头（key:value）
        String  token = request.getHeader("Authorization");
        //2.进行各种情况判断
        if(token == null){
            //当token为null,用户未登录，无法提供保存的token字符串
            throw new ServiceException("用户未登录,请重新登录");
        }
        //3.判断token是否有效（格式，时间,签名）
        try {
            JwtUtil.checkSign(token);
        }catch (Exception e){
            //当验证token无效时，抛出3个异常
            //e.printStackTrace();//输出控制台，开发者查看
            throw new ServiceException("token无效,请重新登录");
        }
        //4.通过验证，可以继续访问controller中方法
        return true;
    }

}
